<template>
  <div class="searchRow">
    <div class="inputRow">
      <div class="inputBox">
        <div class="labelText">名称：</div>
        <a-input v-model:value="queryForm.pageModel.query.name0" placeholder="请输入菜谱名称" @change="inputChange"
          @pressEnter="handleFind" :allowClear="true"></a-input>
      </div>
      <div class="inputBox">
        <div class="labelText">难度：</div>
        <a-select class="selectClass" v-model:value="queryForm.pageModel.query.difficulty1" placeholder="请选择难度"
          :allowClear="true">
          <a-select-option v-for="item in difficultyOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </div>
      <div class="inputBox">
        <div class="labelText">工艺：</div>
        <a-select class="selectClass" v-model:value="queryForm.pageModel.query.craft1" placeholder="请选择工艺"
          :allowClear="true">
          <a-select-option v-for="item in craftOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </div>
      <div class="inputBox">
        <div class="labelText">口味：</div>
        <a-select class="selectClass" v-model:value="queryForm.pageModel.query.taste1" placeholder="请选择口味"
          :allowClear="true">
          <a-select-option v-for="item in tasteOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </div>
      <div class="inputBox">
        <div class="labelText">分类：</div>
        <a-cascader class="selectClass" v-model:value="selectCategory" multiple :options="cookbookCategoryOptions"
          :showSearch="true" @change="changeCategory" :show-checked-strategy="SHOW_CHILD" expand-trigger="hover"
          placeholder="菜谱分类" />
      </div>
    </div>
    <div class="btnBox">
      <a-button type="primary" @click="handleFind" class="queryBtn">
        {{ $t('common.query') }}
      </a-button>
      <a-button class="resetBtn" @click="reset">{{ $t('common.reset') }}</a-button>
    </div>
  </div>

  <div class="operateArea">
    <a-button type="primary" @click="showAddModel" class="queryBtn" :loading="loading">
      {{ $t('common.add') }}
    </a-button>
  </div>
  <div class="cardData">
    <a-flex wrap="wrap" gap="middle">
      <a-card hoverable v-for="(item, index) in cookbookDataList" :key="index" style="width: 200px;"
        @click="goDetail(item.id)">
        <template #cover>
          <img style="height: 150px;" alt="example" src="@/assets/img/菜谱图标.png" />
        </template>
        <template #actions>
          <delete-outlined class="cardOperationBtn" key="setting" @click.stop="delCard(item.id)" />
          <edit-outlined class="cardOperationBtn" key="edit" @click.stop="showEditModel(item)" />
          <!--           <ellipsis-outlined key="ellipsis" />-->
        </template>
        <a-card-meta :title="item.name">
          <template #description>
            <a-tooltip :title="item.remark" placement="top" :mouse-enter-delay="0.3">
              <span class="multi-line-ellipsis">{{ item.remark }}</span>
            </a-tooltip>
          </template>
        </a-card-meta>
      </a-card>
    </a-flex>
  </div>

  <div class="pageSelector">
    <a-pagination v-model:current="queryForm.pageModel.pageNow" :showSizeChanger="true" show-quick-jumper :total="total"
      @change="onChange" />
  </div>

  <a-modal v-model:open="editModel" title="编辑菜谱" @ok="handleEdit">
    <template #footer>
      <a-button class="cancelBtn" key="back" @click="editModel = false">{{ $t('common.cancel') }}</a-button>
      <a-button class="confirmBtn" key="submit" type="primary" :loading="loading" @click="handleEdit">{{
        $t('common.confirm') }}
      </a-button>
    </template>
    <a-form ref="formRef" :model="editAddRecord" :rules="rules">
      <a-form-item :label="$t('common.name')" name="name">
        <a-input v-model:value="editAddRecord.name" />
      </a-form-item>
      <a-form-item label="难度" name="difficulty">
        <a-select v-model:value="editAddRecord.difficulty" placeholder="请选择难度" :allowClear="true">
          <a-select-option v-for="item in difficultyOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="工艺" name="craft">
        <a-select v-model:value="editAddRecord.craft" placeholder="请选择工艺" :allowClear="true">
          <a-select-option v-for="item in craftOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="口味" name="taste">
        <a-select v-model:value="editAddRecord.taste" placeholder="请选择口味" :allowClear="true">
          <a-select-option v-for="item in tasteOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="耗时" name="timeConsuming">
        <a-input v-model:value="editAddRecord.timeConsuming" placeholder="耗时" />
      </a-form-item>
      <a-form-item label="描述" name="remark">
        <a-textarea v-model:value="editAddRecord.remark" />
      </a-form-item>

      <a-form-item label="分类" name="category">
        <a-cascader v-model:value="addEditSelectCategory" :options="cookbookCategoryOptions" expand-trigger="hover"
          :show-checked-strategy="SHOW_CHILD" multiple placeholder="菜谱分类" />
      </a-form-item>

      <a-form-item label="食材" name="ingredient">
        <div class="ingredientSelect" v-for="(item, index) in editAddRecord.ingredientVOList" :key="index">
          <div class="ingredientInput">
            <a-form-item-rest>
              <a-tree-select v-model:value="item.name" style="width: 70%" :tree-data="ingredientWithCategory"
                tree-default-expand-all allow-clear :show-checked-strategy="SHOW_PARENT" placeholder="请选择食材"
                tree-node-filter-prop="label" show-search
                @change="(value, label, extra) => treeNodeChange(value, label, extra, index)" />
            </a-form-item-rest>
            <a-form-item-rest>
              <a-input v-model:value="item.ingredientUsage" :placeholder="common.TheAmountOfIngredientsUsed"
                style="width: 30%;" />
            </a-form-item-rest>
          </div>

          <div class="ingredientAddSub">
            <MinusOutlined class="subOper" @click="subInput(index, item)" />
            <PlusOutlined v-if="editAddRecord.ingredientVOList.length - 1 === index" class="addOper"
              @click="addInput(0)" />
            <PlusOutlined v-else style="color: #fff;" />
          </div>
        </div>
      </a-form-item>

      <a-form-item label="流程" name="process">
        <draggable v-model="editAddRecord.cookbookProcessList" item-key="processOrder" handle=".drag-handle"
          @end="updateProcessOrder" class="process-draggable">
          <template #item="{ element, index }">
            <div class="ingredientSelect">
              <div class="ingredientInput">
                <!-- 添加拖动手柄 -->
                <DragOutlined class="drag-handle" style="margin-right:8px;cursor:move;" />
                <a-form-item-rest>
                  <a-input style="width:11%;margin-right:10px;text-align:center;background:#fff;color:#000;"
                    :value="index + 1" disabled />
                </a-form-item-rest>
                <a-form-item-rest>
                  <!-- 注意这里改为 element.description -->
                  <a-textarea v-model:value="element.description" :placeholder="$t('common.ProductionProcess')"
                    :rows="1" />
                </a-form-item-rest>
              </div>
              <div class="ingredientAddSub">
                <MinusOutlined class="subOper" @click="subInputProcessList(index, element)" />
                <PlusOutlined v-if="editAddRecord.cookbookProcessList.length - 1 === index" class="addOper"
                  @click="addInput(1)" />
                <PlusOutlined v-else style="color: #fff;" />
              </div>
            </div>
          </template>
        </draggable>
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 添加 -->
  <a-modal v-model:open="addModel" title="新建菜谱" @ok="handleAdd">
    <template #footer>
      <a-button class="cancelBtn" key="back" @click="addModel = false">{{ $t('common.cancel') }}</a-button>
      <a-button class="confirmBtn" key="submit" type="primary" :loading="loading" @click="handleAdd">{{
        $t('common.confirm') }}</a-button>
    </template>
    <a-form ref="formRef" :model="editAddRecord" :rules="rules">
      <a-form-item :label="$t('common.name')" name="name">
        <a-input v-model:value="editAddRecord.name" />
      </a-form-item>
      <a-form-item label="难度" name="difficulty">
        <a-select v-model:value="editAddRecord.difficulty" placeholder="请选择难度" :allowClear="true">
          <a-select-option v-for="item in difficultyOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="工艺" name="craft">
        <a-select v-model:value="editAddRecord.craft" placeholder="请选择工艺" :allowClear="true">
          <a-select-option v-for="item in craftOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="口味" name="taste">
        <a-select v-model:value="editAddRecord.taste" placeholder="请选择口味" :allowClear="true">
          <a-select-option v-for="item in tasteOptions" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :label="$t('cookbook.timeConsuming')" name="timeConsuming">
        <a-input v-model:value="editAddRecord.timeConsuming" :placeholder="$t('cookbook.timeConsuming')" />
      </a-form-item>
      <a-form-item label="描述" name="remark">
        <a-textarea v-model:value="editAddRecord.remark" />
      </a-form-item>

      <a-form-item label="分类" name="category">
        <a-cascader v-model:value="addEditSelectCategory" :options="cookbookCategoryOptions" expand-trigger="hover"
          :show-checked-strategy="SHOW_CHILD" multiple placeholder="菜谱分类" />
      </a-form-item>

      <a-form-item label="食材" name="ingredient">
        <div class="ingredientSelect" v-for="(item, index) in editAddRecord.ingredientVOList" :key="index">
          <div class="ingredientInput">
            <a-form-item-rest>
              <a-tree-select v-model:value="item.name" style="width: 70%" :tree-data="ingredientWithCategory"
                show-search tree-default-expand-all allow-clear :show-checked-strategy="SHOW_PARENT" placeholder="请选择食材"
                tree-node-filter-prop="label"
                @change="(value, label, extra) => treeNodeChange(value, label, extra, index)" />
            </a-form-item-rest>
            <a-form-item-rest>
              <a-input v-model:value="item.ingredientUsage" placeholder="食材用量" style="width: 30%;" />
            </a-form-item-rest>
          </div>

          <div class="ingredientAddSub">
            <MinusOutlined class="subOper" @click="subInput(index, item)" />
            <PlusOutlined v-if="editAddRecord.ingredientVOList.length - 1 === index" class="addOper"
              @click="addInput(0)" />
            <PlusOutlined v-else style="color: #fff;" />
          </div>
        </div>
      </a-form-item>

      <a-form-item label="流程" name="process">
        <draggable v-model="editAddRecord.cookbookProcessList" item-key="processOrder" handle=".drag-handle"
          @end="updateProcessOrder" class="process-draggable">
          <template #item="{ element, index }">
            <div class="ingredientSelect">
              <div class="ingredientInput">
                <!-- 添加拖动手柄 -->
                <DragOutlined class="drag-handle" style="margin-right:8px;cursor:move;" />
                <a-form-item-rest>
                  <a-input style="width:11%;margin-right:10px;text-align:center;background:#fff;color:#000;"
                    :value="index + 1" disabled />
                </a-form-item-rest>
                <a-form-item-rest>
                  <!-- 注意这里改为 element.description -->
                  <a-textarea v-model:value="element.description" :placeholder="$t('common.ProductionProcess')"
                    :rows="1" />
                </a-form-item-rest>
              </div>
              <div class="ingredientAddSub">
                <MinusOutlined class="subOper" @click="subInputProcessList(index, element)" />
                <PlusOutlined v-if="editAddRecord.cookbookProcessList.length - 1 === index" class="addOper"
                  @click="addInput(1)" />
                <PlusOutlined v-else style="color: #fff;" />
              </div>
            </div>
          </template>
        </draggable>
      </a-form-item>
    </a-form>
  </a-modal>

</template>

<script setup>
import { deleteCookbook, pageCookbookList, findCookbookDetail, editCookbook, addCookbook } from '@/api/cookbook';
import { findCookbookCategoryList } from '@/api/cookbookCategory';
import { findIngredientWithCategory } from '@/api/ingredient';
import Spin from '@/utils/loading.js';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message, TreeSelect, Cascader } from 'ant-design-vue';
import { createVNode, onActivated, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Draggable from 'vuedraggable'; // 确保正确导入
const router = useRouter();
const route = useRoute();
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
// 只展示子节点
const SHOW_CHILD = Cascader.SHOW_CHILD;
// 菜谱分类
const selectCategory = ref([]);
// 菜谱分类-编辑/新增
const addEditSelectCategory = ref([]);
// 难度列表
const difficultyOptions = ref([
  '简单',
  '中等',
  '困难'
]);
// 工艺列表
const craftOptions = ref([
  '炒', '煎', '炸', '烹', '爆', '烧', '炖', '焖', '煮', '蒸', '烤', '涮', '拌', '腌', '醉', '卤', '酱', '熏', '腊', '煲', '焗',
]);
// 口味列表
const tasteOptions = ref([
  '甜味',
  '酸味',
  '苦味',
  '辣味',
  '咸味',
  '鲜味',
  '麻味',
  '五香',
  '咖喱味',
  '怪味',
  '鱼香味',
  '茄汁味',
  '酱香味',
  '奶香味',
  '烟熏味',
  '酒香'
]);
// 菜谱分类
const cookbookCategoryOptions = ref([]);

// 数据列表
const cookbookDataList = ref([]);
// 分页查询参数
const queryForm = reactive({
  cookbookCategoryIdList: [],
  pageModel: {
    pageNow: 1,
    pageSize: 10,
    query: {
      name0: '',
      difficulty1: null,
      taste1: null,
      craft1: null,
    },
    sort: ['1create_time'],
  }
})
watch(() => queryForm.pageModel.query.taste1, () => {
  getCookbookData();
})
watch(() => queryForm.pageModel.query.difficulty1, () => {
  getCookbookData();
})
watch(() => queryForm.pageModel.query.craft1, () => {
  getCookbookData();
})
watch(() => selectCategory.value, () => {
  queryForm.cookbookCategoryIdList = selectCategory.value.map(e => e[1]);
  getCookbookData();
})
// 总记录数
const total = ref(10);
// 加载
const loading = ref(false);
// 编辑框展示
const editModel = ref(false);
// 新增框展示
const addModel = ref(false);
// 编辑/新增参数
const editAddRecord = reactive({
  id: null, // 菜谱ID
  name: null, // 菜谱名称
  craft: null, // 工艺
  taste: null, // 口味
  difficulty: null, // 难度
  timeConsuming: '', // 耗时
  remark: '', // 备注
  cookbookProcessList: [], // 流程列表
  ingredientVOList: [], // 食材列表
  cookbookCategoryIdList: [], // 菜谱分类列表
});
// 食材对应食材分类列表-树
const ingredientWithCategory = ref([]);
// 规则校验
const rules = {
  name: [
    {
      required: true,
      message: '请输入菜谱名称',
      trigger: 'change',
    },
  ],
};

onMounted(() => {
  if (route.query.parentId && route.query.subId) {
    // 获取食材对应食材分类
    getIngredientWithCategory();
    // 获取菜谱分类
    getCookbookCategoryData();
    // 获取菜谱数据
    selectCategory.value = [[route.query.parentId, route.query.subId]];
  } else {
    initData();
  }
})

onActivated(() => {

})

// 初始化数据
const initData = () => {
  // 分页数据
  getCookbookData();
  // 获取食材对应食材分类
  getIngredientWithCategory();
  // 获取菜谱分类
  getCookbookCategoryData();
}
// 获取菜谱分类
const getCookbookCategoryData = () => {
  findCookbookCategoryList().then(res => {
    if (res.code === 200) {
      cookbookCategoryOptions.value = res.data;
    }
  })
}
// 获取食材对应食材分类
const getIngredientWithCategory = () => {
  findIngredientWithCategory().then(res => {
    if (res.code === 200) {
      console.log(res.data);
      ingredientWithCategory.value = res.data;
    }
  })
}

// 获取分页数据
const getCookbookData = () => {
  Spin.show();
  pageCookbookList(queryForm).then(res => {
    console.log(res);
    if (res.code === 200) {
      cookbookDataList.value = res.data.list.dataList;
      total.value = res.data.list.total;
      Spin.hide();
    }
  })
}

// 删除
const delCard = (id) => {
  Modal.confirm({
    title: '系统消息',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定要删除吗?',
    okText: '是',
    okType: 'danger',
    cancelText: '否',
    onOk() {
      deleteCookbook(id).then(res => {
        if (res.code === 200) {
          message.success('删除成功');
          getCookbookData();
        }
      });
    },
    onCancel() {
    },
  });
}
// 展示编辑内容
const showEditModel = (item) => {
  console.log("showEditModel");
  editModel.value = true;
  findCookbookDetail(item.id).then(res => {
    console.log(res);
    if (res.code === 200) {
      let data = res.data;
      editAddRecord.id = data.id;
      editAddRecord.name = data.name;
      editAddRecord.craft = data.craft;
      editAddRecord.taste = data.taste;
      editAddRecord.difficulty = data.difficulty;
      editAddRecord.timeConsuming = data.timeConsuming;
      editAddRecord.remark = data.remark;
      if (data.cookbookProcessList.length > 0) {
        editAddRecord.cookbookProcessList = data.cookbookProcessList;
      } else {
        editAddRecord.cookbookProcessList = [{
          cookbookId: data.id,
          processOrder: 1,
          img: null,
          description: null,
        }];
      }
      if (data.ingredientVOList.length > 0) {
        editAddRecord.ingredientVOList = data.ingredientVOList;
      } else {
        editAddRecord.ingredientVOList = [{ name: null, ingredientUsage: null }];
      }
      // 菜谱分类
      let cookbookCategoryList = data.cookbookCategoryList;
      addEditSelectCategory.value = cookbookCategoryList.map(e => [e.parentId, e.id])
    }
  })
}
// 展示新建内容
const showAddModel = () => {
  addModel.value = true;
  editAddRecord.id = null;
  editAddRecord.name = null;
  editAddRecord.craft = null;
  editAddRecord.taste = null;
  editAddRecord.difficulty = null;
  editAddRecord.timeConsuming = null;
  editAddRecord.remark = null;
  addEditSelectCategory.value = [];
  editAddRecord.cookbookProcessList = [{
    cookbookId: null,
    processOrder: 1,
    img: null,
    description: null,
  }];
  editAddRecord.ingredientVOList = [{ name: null, ingredientUsage: null }];
}
// 编辑
const handleEdit = () => {
  editAddRecord.cookbookCategoryIdList = addEditSelectCategory.value.map(e => e[1]);
  editCookbook(editAddRecord).then(res => {
    if (res.code === 200) {
      message.success('编辑成功');
      editModel.value = false;
      getCookbookData();
    }
  })
}
// 新建
const handleAdd = () => {
  loading.value = true;
  addCookbook(editAddRecord).then(res => {
    if (res.code === 200) {
      message.success('新建成功');
      addModel.value = false;
      getCookbookData();
      loading.value = false;
    }
  })
}
// 分页器发生变化
const onChange = (page, pageSize) => {
  console.log(page, pageSize);
  queryForm.pageModel.pageNow = page;
  queryForm.pageModel.pageSize = pageSize;
  getCookbookData();
}
// 重置
const reset = () => {
  queryForm.pageModel.query.name0 = null;
  queryForm.pageModel.query.taste1 = null;
  queryForm.pageModel.query.difficulty1 = null;
  queryForm.cookbookCategoryIdList = [];
  selectCategory.value = [];
  initData();
}
// 输入框发生变化
const inputChange = () => {
  getCookbookData();
}
// 查询
const handleFind = () => {
  getCookbookData();
}
// 去详情
const goDetail = (id) => {
  router.push('/cookbook-manage/cookbook-detail?id=' + id)
}
// 拖拽后同步更新排序号
const updateProcessOrder = () => {
  editAddRecord.cookbookProcessList.forEach((item, index) => {
    item.processOrder = index + 1
  })
}
// 删除食材
const subInput = (index, item) => {
  if (editAddRecord.ingredientVOList.length < 2) {
    return;
  }
  editAddRecord.ingredientVOList.splice(index, 1);
}
// 删除流程
const subInputProcessList = (index, item) => {
  if (editAddRecord.cookbookProcessList.length < 2) {
    return;
  }
  editAddRecord.cookbookProcessList.splice(index, 1);
}
// 添加食材/流程
const addInput = (type) => {
  if (type === 0) {
    editAddRecord.ingredientVOList.push({
      id: null,
      name: null,
      ingredientUsage: null,
    });
  } else if (type === 1) {
    editAddRecord.cookbookProcessList.push({
      cookbookId: editAddRecord.id,
      processOrder: editAddRecord.cookbookProcessList.length + 1,
      img: null,
      description: null,
    })
  }
}
// 食材树节点变化
const treeNodeChange = (value, label, extra, index) => {
  console.log(value, label, extra, index, editAddRecord.ingredientVOList);
  let ingredientItem = editAddRecord.ingredientVOList[index];
  ingredientItem.name = label[0];
  let ingredientId = Math.abs(value);
  ingredientItem.id = ingredientId;
}
const changeCategory = (value) => {
  console.log('selectCategory.value');
  console.log(selectCategory.value);
}
</script>

<style scoped lang="scss">
.searchRow {
  display: flex;
  background-color: #fff;
  padding: 20px;
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;

  .inputRow {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .inputBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-right: 70px;
      margin-top: 10px;
      margin-bottom: 10px;

      .labelText {
        white-space: nowrap;
        font-size: 14px;
      }

      .selectClass {
        width: 199px;
      }
    }
  }

  .btnBox {
    display: flex;
    flex-wrap: nowrap;

    button {
      margin: 10px 0 10px 9px;
    }

    .ant-btn:first-child {
      margin-right: 8px !important;
    }
  }
}

// 卡片移入边框
.ant-card:hover {
  border-color: #fff !important;
}

// 卡片操作按钮移入颜色
.cardOperationBtn:hover {
  color: green !important;
}

.pageSelector {
  display: flex;
  background-color: #fff;
  padding: 20px 0;
  border-top: 1px solid rgb(240, 233, 233);
  justify-content: end;
}

.cardData {
  background-color: #fff;
  padding: 20px
}

.ingredientSelect {
  display: flex;
  margin-bottom: 5px;
  width: 100%;

  .ingredientInput {
    display: flex;
    width: 100%;
    align-items: center;
  }

  .ingredientAddSub {
    display: flex;
    justify-content: center;
    align-items: center;

    .subOper {
      color: grey;
      margin-left: 10px;
      margin-right: 6px;
      cursor: pointer;
    }

    .addOper {
      color: green;
      cursor: pointer;
    }
  }
}

// ------------------
/* 添加这些关键样式 */
.process-draggable {
  width: 100%;
}

/* 拖动时的视觉反馈 */
.drag-handle:hover {
  color: #4ab44a;
}

/* 拖动时的占位样式 */
.sortable-chosen {
  background: #fafafa;
  border: 1px dashed #e8e8e8;
}

/* 拖动时的预览样式 */
.sortable-ghost {
  opacity: 0.5;
  background: #e8f0e8;
}

.operateArea {
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: end;
  padding: 20px 20px 20px 0px;
  border-bottom: 1px solid #d9d9d9;
}

.ant-cascader-checkbox .ant-cascader-checkbox-inner {
  display: none;
}

.multi-line-ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  /* 显示行数 */
  overflow: hidden;
  max-width: 100%;
  line-height: 1.5;
}
</style>
